<template>
  <view class="mayor-log-container">
    <!-- 主标签页导航 - 底部固定 -->
    <view class="main-tabs-nav">
      <view 
        v-for="tab in tabs" 
        :key="tab.id"
        class="main-tab"
        :class="{ 'active': currentTab === tab.id }"
        @click="switchTab(tab.id)"
      >
        <text class="tab-icon">{{ tab.icon }}</text>
        <text class="tab-text">{{ tab.text }}</text>
      </view>
    </view>

    <!-- 游戏内容区域 -->
    <view id="game-container" class="game-container">
      <!-- Canvas动画层 - 暂时禁用，提升性能 -->
      <!-- <canvas 
        id="game-canvas" 
        canvas-id="game-canvas"
        class="game-canvas"
        :style="{ 
          width: canvasWidth + 'px', 
          height: canvasHeight + 'px',
          visibility: canvasEnabled ? 'visible' : 'hidden',
          pointerEvents: 'none'
        }"
      ></canvas> -->
      
      <view v-if="isLoading" class="loading-screen">
        <view class="loading-spinner"></view>
        <text class="loading-text">正在加载游戏数据...</text>
      </view>

      <!-- 总览标签页 -->
      <view v-show="!isLoading" class="tab-content" :class="{ active: currentTab === 'overview' }">
        <view class="overview-grid">
          <!-- 资源卡片 -->
          <view class="resources-row" id="resources-row">
            <view class="resource-card" v-for="(resource, key) in gameData.resources" :key="key">
              <text class="resource-icon">{{ getResourceIcon(key) }}</text>
              <text class="resource-name">{{ getResourceName(key) }}</text>
              <text class="resource-value">{{ Math.floor(resource.amount) }}</text>
              <text class="resource-change" :class="{ positive: resource.change > 0, negative: resource.change < 0 }">
                {{ resource.change > 0 ? '+' : '' }}{{ resource.change }}/时
              </text>
            </view>
          </view>

          <!-- 状态信息 -->
          <view class="info-cards-grid">
            <view class="info-card-small">
              <view class="info-card-label">
                <text class="info-icon">🏁</text>
                <text class="info-text">当前阶段</text>
              </view>
              <text class="info-card-value">{{ currentStage.name }}</text>
            </view>
            <view class="info-card-small">
              <view class="info-card-label">
                <text class="info-icon">👥</text>
                <text class="info-text">人口</text>
              </view>
              <text class="info-card-value">{{ gameData.resources.population.amount }}/{{ gameData.resources.population.max }}</text>
            </view>
            <view class="info-card-small">
              <view class="info-card-label">
                <text class="info-icon">📅</text>
                <text class="info-text">游戏天数</text>
              </view>
              <text class="info-card-value">第{{ gameData.gameDay }}天</text>
            </view>
            <view class="info-card-small">
              <view class="info-card-label">
                <text class="info-icon">🔔</text>
                <text class="info-text">待处理事件</text>
              </view>
              <text class="info-card-value">{{ pendingEventsCount }}</text>
            </view>
          </view>

          <!-- 快捷操作 -->
          <view class="quick-actions">
            <button id="recruit-villager-quick" class="btn btn-primary" @click="recruitVillager">
              <text class="btn-icon">👤</text>
              <text class="btn-text">招募村民</text>
            </button>
            <button class="btn btn-secondary" @click="collectResources" :disabled="isCollecting">
              <text class="btn-icon">⚡</text>
              <text class="btn-text">{{isCollecting ? '收集ing...' : '收集资源'}}</text>
            </button>
          </view>
        </view>
      </view>

      <!-- 建筑标签页 -->
      <view v-show="!isLoading" class="tab-content" :class="{ active: currentTab === 'buildings' }">
        <view class="content-list" id="buildings-list">
          <view v-for="building in buildings" :key="building.id" class="building-card">
            <view class="building-header">
              <text class="building-icon">{{ getBuildingIcon(building.id) }}</text>
              <view class="building-info">
                <text class="building-name">{{ building.name }}</text>
                <text class="building-level">等级 {{ building.level }}</text>
              </view>
            </view>
            <view class="building-details">
              <text class="building-description">{{ building.description }}</text>
              <view class="building-stats">
                <text class="stat-item" v-for="stat in building.effects" :key="stat.name">
                  {{ stat.name }} +{{ stat.value }}%
                </text>
              </view>
            </view>
            <button 
              class="btn btn-primary" 
              :disabled="!canUpgradeBuilding(building)"
              @click="upgradeBuilding(building.id)"
            >
              <text class="btn-text">升级 (木材: {{ getUpgradeCost(building) }})</text>
            </button>
          </view>
        </view>
      </view>

      <!-- 事件标签页 -->
      <view v-show="!isLoading" class="tab-content" :class="{ active: currentTab === 'events' }">
        <!-- 空状态 -->
        <view v-if="gameData.events.length === 0" class="empty-state">
          <text class="empty-icon">📭</text>
          <text class="empty-text">暂无事件</text>
          <text class="empty-subtext">继续发展你的村庄，事件会随机出现</text>
        </view>
        
        <!-- 有事件时显示 -->
        <view v-else class="events-container">
          <!-- 事件类型Tab -->
          <view class="event-tabs">
            <view 
              class="event-tab" 
              :class="{ active: eventFilter === 'pending' }"
              @tap="switchEventFilter('pending')"
            >
              <text class="event-tab-text">待处理</text>
              <view v-if="pendingEvents.length > 0" class="event-tab-badge">{{ pendingEvents.length }}</view>
            </view>
            <view 
              class="event-tab" 
              :class="{ active: eventFilter === 'resolved' }"
              @tap="switchEventFilter('resolved')"
            >
              <text class="event-tab-text">已处理</text>
              <view v-if="resolvedEvents.length > 0" class="event-tab-badge">{{ resolvedEvents.length }}</view>
            </view>
          </view>
          
          <!-- 事件列表 -->
          <view class="events-list">
            <!-- 待处理事件 - 使用 v-show 替代 v-if 优化性能 -->
            <view v-show="eventFilter === 'pending'">
              <view v-if="pendingEvents.length === 0" class="empty-state-small">
                <text class="empty-icon-small">✅</text>
                <text class="empty-text-small">暂无待处理事件</text>
              </view>
              <view v-else class="event-card" v-for="event in pendingEvents" :key="event.id">
                <view class="event-header">
                  <text class="event-icon">{{ getEventIcon(event.type) }}</text>
                  <view class="event-info">
                    <text class="event-title">{{ event.title }}</text>
                    <text class="event-time">{{ formatEventTime(event.timestamp) }}</text>
                  </view>
                </view>
                <text class="event-description">{{ event.description }}</text>
                <!-- 横向滚动的选项按钮 -->
                <scroll-view class="event-choices-scroll" scroll-x>
                  <view class="event-choices-horizontal">
                    <button 
                      v-for="(choice, index) in event.choices" 
                      :key="index"
                      class="choice-btn-horizontal"
                      @click="makeChoice(event.id, index)"
                    >
                      <text class="choice-btn-text">{{ choice.text }}</text>
                    </button>
                  </view>
                </scroll-view>
              </view>
            </view>
            
            <!-- 已处理事件 - 使用 v-show 替代 v-if 优化性能 -->
            <view v-show="eventFilter === 'resolved'">
              <view v-if="resolvedEvents.length === 0" class="empty-state-small">
                <text class="empty-icon-small">📝</text>
                <text class="empty-text-small">暂无已处理事件</text>
              </view>
              <view v-else class="event-card resolved" v-for="event in resolvedEvents" :key="event.id">
                <view class="event-header">
                  <text class="event-icon">{{ getEventIcon(event.type) }}</text>
                  <view class="event-info">
                    <text class="event-title">{{ event.title }}</text>
                    <text class="event-time">{{ formatEventTime(event.timestamp) }}</text>
                  </view>
                </view>
                <view class="event-outcome">
                  <text class="outcome-icon">✓</text>
                  <text class="outcome-text">{{ event.outcome }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 村民标签页 -->
      <view v-show="!isLoading" class="tab-content" :class="{ active: currentTab === 'villagers' }">
        <view class="empty-state">
          <text class="empty-icon">👥</text>
          <text class="empty-text">村民管理功能即将上线</text>
          <text class="empty-subtext">将支持查看村民信息、分配工作等功能</text>
        </view>
      </view>

      <!-- 日志标签页 -->
      <view v-show="!isLoading" class="tab-content" :class="{ active: currentTab === 'logs' }">
        <view class="logs-container" id="game-log">
          <view v-for="log in gameLogs" :key="log.id" class="log-item">
            <text class="log-time">{{ log.time }}</text>
            <text class="log-text">{{ log.text }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 通知弹窗 -->
    <view id="notification" class="notification" :class="{ 'show': notificationVisible }">
      <text id="notification-icon" class="notification-icon" :style="{ color: notificationColor }">{{ notificationIcon }}</text>
      <view class="notification-content">
        <text id="notification-title" class="notification-title">{{ notificationTitle }}</text>
        <text id="notification-message" class="notification-message">{{ notificationMessage }}</text>
      </view>
    </view>
  </view>
</template>

<script>
// 游戏配置常量
const GAME_CONFIG = {
  AUTO_SAVE_INTERVAL: 30000, // 30秒自动保存
  RESOURCE_UPDATE_INTERVAL: 60000, // 1分钟更新资源
  EVENT_CHECK_INTERVAL: 120000, // 2分钟检查一次事件
  DAY_DURATION_IN_HOURS: 2, // 游戏中一天的小时数
  BASE_FOOD_CHANGE: 15,
  BASE_WOOD_CHANGE: 10,
  FOOD_PER_POPULATION: 2,
  VILLAGER_RECRUIT_BASE_COST_WOOD: 20,
  VILLAGER_RECRUIT_BASE_COST_FOOD: 50,
  VILLAGER_RECRUIT_COST_GROWTH: 1.1
};

/**
 * 缓动函数
 */
const Easing = {
  easeOutCubic: (t) => 1 - Math.pow(1 - t, 3),
  easeInOutCubic: (t) => t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2,
  easeOutElastic: (t) => {
    const c4 = (2 * Math.PI) / 3;
    return t === 0 ? 0 : t === 1 ? 1 : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1;
  }
};

/**
 * 资源变化动画类
 */
class ResourceAnimation {
  constructor(type, value, x, y, isPositive) {
    this.type = type; // 'wood', 'food', 'population'
    this.value = value;
    this.x = x;
    this.y = y;
    this.startY = y;
    this.isPositive = isPositive;
    this.duration = 1500;
    this.elapsed = 0;
    this.opacity = 1;
  }
  
  update(deltaTime) {
    this.elapsed += deltaTime;
    const progress = Math.min(this.elapsed / this.duration, 1);
    
    // 向上飘动
    this.y = this.startY - Easing.easeOutCubic(progress) * 100;
    
    // 淡出
    this.opacity = 1 - Easing.easeInOutCubic(progress);
  }
  
  draw(ctx) {
    if (!ctx || !ctx.fillText) return;
    
    ctx.save();
    ctx.globalAlpha = this.opacity;
    
    // 设置字体
    ctx.font = 'bold 24px sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    // 设置颜色
    const color = this.isPositive ? '#10B981' : '#EF4444';
    ctx.fillStyle = color;
    
    // 绘制文字
    const text = `${this.isPositive ? '+' : ''}${this.value}`;
    ctx.fillText(text, this.x, this.y);
    
    ctx.restore();
  }
  
  isComplete() {
    return this.elapsed >= this.duration;
  }
}

/**
 * 粒子类
 */
class Particle {
  constructor(x, y, targetX, targetY, color, size = 4) {
    this.x = x;
    this.y = y;
    this.startX = x;
    this.startY = y;
    this.targetX = targetX;
    this.targetY = targetY;
    this.color = color;
    this.size = size;
    this.duration = 800 + Math.random() * 400;
    this.elapsed = 0;
    this.opacity = 1;
  }
  
  update(deltaTime) {
    this.elapsed += deltaTime;
    const progress = Math.min(this.elapsed / this.duration, 1);
    
    // 贝塞尔曲线路径
    const t = Easing.easeInOutCubic(progress);
    const controlX = (this.startX + this.targetX) / 2;
    const controlY = Math.min(this.startY, this.targetY) - 100;
    
    this.x = Math.pow(1 - t, 2) * this.startX + 2 * (1 - t) * t * controlX + Math.pow(t, 2) * this.targetX;
    this.y = Math.pow(1 - t, 2) * this.startY + 2 * (1 - t) * t * controlY + Math.pow(t, 2) * this.targetY;
    
    // 淡出
    if (progress > 0.7) {
      this.opacity = 1 - (progress - 0.7) / 0.3;
    }
  }
  
  draw(ctx) {
    if (!ctx || !ctx.arc) return;
    
    ctx.save();
    ctx.globalAlpha = this.opacity;
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
  }
  
  isComplete() {
    return this.elapsed >= this.duration;
  }
}

/**
 * 建筑升级特效类
 */
class BuildingUpgradeEffect {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.duration = 1000;
    this.elapsed = 0;
    this.particles = [];
    
    // 创建粒子环
    for (let i = 0; i < 20; i++) {
      const angle = (Math.PI * 2 * i) / 20;
      this.particles.push({
        angle: angle,
        radius: 0,
        maxRadius: 60 + Math.random() * 20,
        opacity: 1
      });
    }
  }
  
  update(deltaTime) {
    this.elapsed += deltaTime;
    const progress = Math.min(this.elapsed / this.duration, 1);
    
    this.particles.forEach(p => {
      p.radius = Easing.easeOutCubic(progress) * p.maxRadius;
      p.opacity = 1 - progress;
    });
  }
  
  draw(ctx) {
    if (!ctx || !ctx.arc) return;
    
    ctx.save();
    
    this.particles.forEach(p => {
      const x = this.x + Math.cos(p.angle) * p.radius;
      const y = this.y + Math.sin(p.angle) * p.radius;
      
      ctx.globalAlpha = p.opacity;
      ctx.fillStyle = '#F59E0B';
      ctx.beginPath();
      ctx.arc(x, y, 3, 0, Math.PI * 2);
      ctx.fill();
    });
    
    // 中心光晕
    const gradient = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, 40);
    gradient.addColorStop(0, `rgba(245, 158, 11, ${0.5 * (1 - this.elapsed / this.duration)})`);
    gradient.addColorStop(1, 'rgba(245, 158, 11, 0)');
    ctx.fillStyle = gradient;
    ctx.fillRect(this.x - 40, this.y - 40, 80, 80);
    
    ctx.restore();
  }
  
  isComplete() {
    return this.elapsed >= this.duration;
  }
}

/**
 * Canvas渲染器类
 * 负责管理所有Canvas动画效果
 */
class CanvasRenderer {
  constructor(canvas, context) {
    this.canvas = canvas;
    this.ctx = context;
    this.width = 0;
    this.height = 0;
    this.dpr = 1; // 设备像素比
    this.animations = [];
    this.particles = [];
    this.isRunning = false;
    this.lastFrameTime = 0;
    this.animationFrame = null;
  }
  
  /**
   * 初始化Canvas尺寸和DPR
   */
  init(width, height) {
    this.width = width;
    this.height = height;
    
    // 获取设备像素比
    // #ifdef H5
    this.dpr = window.devicePixelRatio || 1;
    // #endif
    
    // #ifndef H5
    this.dpr = uni.getSystemInfoSync().pixelRatio || 1;
    // #endif
    
    // 设置Canvas实际尺寸（考虑DPR）
    if (this.canvas.width !== undefined) {
      this.canvas.width = width * this.dpr;
      this.canvas.height = height * this.dpr;
    }
    
    // 缩放上下文以匹配DPR
    if (this.ctx && this.ctx.scale) {
      this.ctx.scale(this.dpr, this.dpr);
    }
  }
  
  /**
   * 添加动画
   */
  addAnimation(animation) {
    this.animations.push(animation);
    if (!this.isRunning) {
      this.start();
    }
  }
  
  /**
   * 添加粒子
   */
  addParticle(particle) {
    this.particles.push(particle);
    if (!this.isRunning) {
      this.start();
    }
  }
  
  /**
   * 启动渲染循环
   */
  start() {
    if (this.isRunning) return;
    this.isRunning = true;
    this.lastFrameTime = Date.now();
    this.render();
  }
  
  /**
   * 停止渲染循环
   */
  stop() {
    this.isRunning = false;
    if (this.animationFrame) {
      cancelAnimationFrame(this.animationFrame);
      this.animationFrame = null;
    }
  }
  
  /**
   * 渲染循环
   */
  render() {
    if (!this.isRunning) return;
    
    const now = Date.now();
    const deltaTime = now - this.lastFrameTime;
    this.lastFrameTime = now;
    
    // 清空画布
    if (this.ctx && this.ctx.clearRect) {
      this.ctx.clearRect(0, 0, this.width, this.height);
    }
    
    // 更新和绘制动画
    this.animations = this.animations.filter(animation => {
      animation.update(deltaTime);
      animation.draw(this.ctx);
      return !animation.isComplete();
    });
    
    // 更新和绘制粒子
    this.particles = this.particles.filter(particle => {
      particle.update(deltaTime);
      particle.draw(this.ctx);
      return !particle.isComplete();
    });
    
    // 如果还有动画或粒子，继续渲染
    if (this.animations.length > 0 || this.particles.length > 0) {
      this.animationFrame = requestAnimationFrame(() => this.render());
    } else {
      this.isRunning = false;
    }
  }
  
  /**
   * 清理资源
   */
  destroy() {
    this.stop();
    this.animations = [];
    this.particles = [];
    this.ctx = null;
    this.canvas = null;
  }
}

// 建筑类型配置（移到组件外部作为常量）
const BUILDING_TYPES = [
    {
      id: 'farm',
      name: '农场',
      description: '生产食物，每级增加食物产出50%',
      baseCost: 20,
      baseFoodProduction: 5,
      effects: [{ name: '食物产出', value: 50 }]
    },
    {
      id: 'sawmill',
      name: '伐木场',
      description: '生产木材，每级增加木材产出50%',
      baseCost: 30,
      baseWoodProduction: 8,
      effects: [{ name: '木材产出', value: 50 }]
    },
    {
      id: 'house',
      name: '民房',
      description: '增加人口上限',
      baseCost: 40,
      populationIncrease: 5,
      effects: [{ name: '人口上限', value: 5 }]
    },
    {
      id: 'market',
      name: '市场',
      description: '提高资源交易效率',
      baseCost: 60,
      effects: [{ name: '交易效率', value: 30 }]
    },
    {
      id: 'school',
      name: '学校',
      description: '提高村民工作效率',
      baseCost: 80,
      effects: [{ name: '工作效率', value: 20 }]
    }
];

// 事件类型配置（移到组件外部作为常量）
const EVENT_TYPES = [
    {
      type: 'resource',
      title: '资源发现',
      description: '村民在森林中发现了一些额外的资源！',
      choices: [
        {
          text: '收集木材',
          effects: { wood: 20 },
          outcome: '成功收集了20单位木材！'
        },
        {
          text: '寻找食物',
          effects: { food: 15 },
          outcome: '成功收集了15单位食物！'
        }
      ]
    },
    {
      type: 'disaster',
      title: '自然灾害',
      description: '一场暴风雨袭击了村庄，需要做出应对！',
      choices: [
        {
          text: '修复建筑',
          effects: { wood: -15 },
          outcome: '成功修复了受损的建筑。'
        },
        {
          text: '疏散村民',
          effects: { food: -10 },
          outcome: '村民安全疏散，但消耗了一些食物。'
        }
      ]
    },
    {
      type: 'opportunity',
      title: '商队到访',
      description: '一支商队经过村庄，想要进行交易。',
      choices: [
        {
          text: '用食物换木材',
          effects: { food: -15, wood: 25 },
          outcome: '成功完成交易！'
        },
        {
          text: '用木材换食物',
          effects: { wood: -15, food: 25 },
          outcome: '成功完成交易！'
        },
        {
          text: '拒绝交易',
          effects: {},
          outcome: '商队离开了。'
        }
      ]
    },
    {
      type: 'villager',
      title: '流浪者',
      description: '一个流浪者请求加入你的村庄。',
      choices: [
        {
          text: '接纳',
          effects: { food: -5, population: 1 },
          outcome: '流浪者成为了村庄的一员。'
        },
        {
          text: '拒绝',
          effects: {},
          outcome: '流浪者离开了。'
        }
      ]
    }
];

export default {
  
  data() {
    return {
      currentTab: 'overview',
      isLoading: true,
      isCollecting: false,
      eventFilter: 'pending', // 'pending' 或 'resolved'
      eventFilterSwitching: false, // 防止快速点击
      gameData: {
        resources: {
          wood: { amount: 50, change: 10, max: null },
          food: { amount: 50, change: 15, max: null },
          population: { amount: 5, change: 0, max: 10 }
        },
        buildings: [],
        events: [],
        gameDay: 1,
        day: 1,
        month: 1,
        year: 1,
        lastUpdated: Date.now()
      },
      gameLogs: [],
      notificationVisible: false,
      notificationTitle: '',
      notificationMessage: '',
      notificationIcon: 'ℹ️',
      notificationColor: '#6366F1',
      storageKey: 'mayorLogGame',
      timers: {
        resourceUpdate: null,
        autoSave: null
      },
      tabs: [
        { id: 'overview', icon: '🏠', text: '总览' },
        { id: 'buildings', icon: '🏗️', text: '建筑' },
        { id: 'events', icon: '🔔', text: '事件' },
        { id: 'villagers', icon: '👥', text: '村民' },
        { id: 'logs', icon: '📋', text: '日志' }
      ],
      currentStage: {
        id: 'survival',
        name: '生存阶段',
        description: '努力生存，发展基础设施'
      },
      // Canvas相关
      canvasEnabled: false,
      canvasWidth: 0,
      canvasHeight: 0,
      canvasRenderer: null
    }
  },
  
  computed: {
    pendingEventsCount() {
      return this.gameData.events.filter(event => !event.resolved).length;
    },
    
    // 待处理事件
    pendingEvents() {
      return this.gameData.events.filter(event => !event.resolved);
    },
    
    // 已处理事件
    resolvedEvents() {
      return this.gameData.events.filter(event => event.resolved);
    },
    
    buildings() {
      return BUILDING_TYPES.map(type => {
        const existingBuilding = this.gameData.buildings.find(b => b.id === type.id) || {
          id: type.id,
          level: 0,
          built: false
        };
        return {
          ...type,
          ...existingBuilding
        };
      }).filter(building => building.built || this.canAffordBuilding(building));
    },
    
    // 村庄等级
    villageLevel() {
      return this.getVillageLevel();
    }
  },
  
  onLoad() {
    // 镇长日志是纯前端游戏，不需要后端服务器，停止健康检查
    this.stopHealthCheck();
    this.initGame();
  },
  
  onUnload() {
    this.clearTimers();
    this.destroyCanvas();
    this.saveGame();
    // 恢复健康检查（离开游戏页面后）
    this.resumeHealthCheck();
  },
  
  methods: {
    /**
     * 停止健康检查（游戏不需要后端服务器）
     */
    stopHealthCheck() {
      try {
        // 尝试获取全局的 appStateManager
        const pages = getCurrentPages();
        if (pages.length > 0) {
          const app = getApp();
          if (app && app.globalData && app.globalData.appStateManager) {
            app.globalData.appStateManager.stopPeriodicHealthCheck();
            console.log('已停止健康检查（镇长日志游戏不需要后端）');
          }
        }
      } catch (error) {
        console.log('停止健康检查失败（可忽略）:', error);
      }
    },
    
    /**
     * 恢复健康检查
     */
    resumeHealthCheck() {
      try {
        const pages = getCurrentPages();
        if (pages.length > 0) {
          const app = getApp();
          if (app && app.globalData && app.globalData.appStateManager) {
            app.globalData.appStateManager.startPeriodicHealthCheck();
            console.log('已恢复健康检查');
          }
        }
      } catch (error) {
        console.log('恢复健康检查失败（可忽略）:', error);
      }
    },
    
    // 切换标签页
    switchTab(tab) {
      this.currentTab = tab;
    },
    
    // 切换事件筛选 - 优化防抖机制和响应速度
    switchEventFilter(filter) {
      // 如果已经是当前筛选，不需要切换
      if (this.eventFilter === filter) {
        return;
      }
      
      // 如果正在切换中，忽略新的点击
      if (this.eventFilterSwitching) {
        return;
      }
      
      // 设置切换状态
      this.eventFilterSwitching = true;
      
      // 立即更新筛选状态，提供即时反馈
      this.eventFilter = filter;
      
      // 使用 $nextTick 确保 DOM 更新后再解锁
      this.$nextTick(() => {
        // 50ms 后解除切换锁定（减少延迟，提高响应速度）
        setTimeout(() => {
          this.eventFilterSwitching = false;
        }, 50);
      });
    },
    
    /**
     * 初始化Canvas
     */
    initCanvas() {
      try {
        // 获取系统信息
        const systemInfo = uni.getSystemInfoSync();
        this.canvasWidth = systemInfo.windowWidth;
        this.canvasHeight = systemInfo.windowHeight - 60 - 70; // 减去导航栏和标签栏高度
        
        // 延迟获取Canvas上下文，确保DOM已渲染
        // 使用 $nextTick 确保 Vue 完成 DOM 更新
        this.$nextTick(() => {
          setTimeout(() => {
            try {
              // #ifdef H5
              const canvas = document.getElementById('game-canvas');
              if (canvas && canvas.getContext) {
                const ctx = canvas.getContext('2d');
                if (ctx) {
                  this.canvasRenderer = new CanvasRenderer(canvas, ctx);
                  this.canvasRenderer.init(this.canvasWidth, this.canvasHeight);
                  this.canvasEnabled = true;
                  console.log('Canvas初始化成功 (H5)');
                } else {
                  console.log('Canvas上下文获取失败，禁用Canvas动画');
                  this.canvasEnabled = false;
                }
              } else {
                console.log('Canvas元素未找到或不支持，禁用Canvas动画');
                this.canvasEnabled = false;
              }
              // #endif
              
              // #ifndef H5
              const ctx = uni.createCanvasContext('game-canvas', this);
              if (ctx) {
                this.canvasRenderer = new CanvasRenderer(null, ctx);
                this.canvasRenderer.init(this.canvasWidth, this.canvasHeight);
                this.canvasEnabled = true;
                console.log('Canvas初始化成功 (小程序/App)');
              } else {
                console.log('Canvas上下文创建失败，禁用Canvas动画');
                this.canvasEnabled = false;
              }
              // #endif
            } catch (innerError) {
              console.log('Canvas初始化内部错误（可忽略）:', innerError);
              this.canvasEnabled = false;
            }
          }, 500); // 增加延迟到500ms，确保DOM完全渲染
        });
      } catch (error) {
        console.error('Canvas初始化失败:', error);
        this.canvasEnabled = false;
      }
    },
    
    /**
     * 销毁Canvas
     */
    destroyCanvas() {
      if (this.canvasRenderer) {
        this.canvasRenderer.destroy();
        this.canvasRenderer = null;
      }
      this.canvasEnabled = false;
    },
    
    async initGame() {
      this.isLoading = true;
      try {
        await this.loadGameData();
        this.initializeBuildings();
        this.updateResourcesBasedOnTime();
        this.setupTimers();
        // 暂时禁用 Canvas，提升性能和稳定性
        // this.initCanvas();
        this.addLog('游戏初始化完成');
        this.showNotification('欢迎来到镇长日志游戏！', '', 'success');
      } catch (error) {
        console.error('游戏初始化失败:', error);
        this.showNotification('游戏初始化失败，请重试', '', 'error');
      } finally {
        this.isLoading = false;
      }
    },
    
    loadGameData() {
      try {
        const savedData = uni.getStorageSync(this.storageKey);
        if (savedData) {
          this.gameData = JSON.parse(savedData);
        }
      } catch (error) {
        console.error('加载游戏数据失败:', error);
        // 使用初始数据
      }
    },
    
    saveGame() {
      try {
        this.gameData.lastUpdated = Date.now();
        uni.setStorageSync(this.storageKey, JSON.stringify(this.gameData));
      } catch (error) {
        console.error('保存游戏数据失败:', error);
      }
    },
    
    initializeBuildings() {
      // 如果没有建筑数据，初始化建筑
      if (!this.gameData.buildings || this.gameData.buildings.length === 0) {
        this.gameData.buildings = [
          {
            id: 'farm',
            level: 1,
            built: true
          },
          {
            id: 'sawmill',
            level: 1,
            built: true
          }
        ];
      }
    },
    
    updateResourcesBasedOnTime() {
      const now = Date.now();
      const lastUpdate = this.gameData.lastUpdated || now;
      const timePassed = now - lastUpdate;
      const hoursPassed = timePassed / (1000 * 60 * 60);
      
      // 更新资源
      Object.keys(this.gameData.resources).forEach(key => {
        const resource = this.gameData.resources[key];
        resource.amount += resource.change * hoursPassed;
        if (resource.amount < 0) resource.amount = 0;
        if (resource.max !== null && resource.amount > resource.max) {
          resource.amount = resource.max;
        }
      });
      
      // 更新游戏天数（简单计算：每2小时为1天）
      const daysPassed = Math.floor(hoursPassed / 2);
      if (daysPassed > 0) {
        this.gameData.gameDay += daysPassed;
        this.addLog(`进入第${this.gameData.gameDay}天`);
      }
      
      this.gameData.lastUpdated = now;
      this.updateResourceChanges();
    },
    
    updateResourceChanges() {
      const farm = this.gameData.buildings.find(b => b.id === 'farm');
      const sawmill = this.gameData.buildings.find(b => b.id === 'sawmill');
      
      let foodChange = GAME_CONFIG.BASE_FOOD_CHANGE; // 使用配置中的基础产出
      let woodChange = GAME_CONFIG.BASE_WOOD_CHANGE; // 使用配置中的基础产出
      
      // 建筑加成
      if (farm) {
        foodChange *= (1 + farm.level * 0.5);
      }
      if (sawmill) {
        woodChange *= (1 + sawmill.level * 0.5);
      }
      
      // 人口消耗
      const population = this.gameData.resources.population.amount;
      foodChange -= population * GAME_CONFIG.FOOD_PER_POPULATION; // 使用配置中的人口消耗值
      
      this.gameData.resources.food.change = Math.round(foodChange);
      this.gameData.resources.wood.change = Math.round(woodChange);
    },
    
    setupTimers() {
      // 每分钟更新一次资源
      this.timers.resourceUpdate = setInterval(() => {
        this.updateResources();
      }, GAME_CONFIG.RESOURCE_UPDATE_INTERVAL);
      
      // 每30秒自动保存
      this.timers.autoSave = setInterval(() => {
        this.saveGame();
      }, GAME_CONFIG.AUTO_SAVE_INTERVAL);
      
      // 每2分钟检查一次事件
      this.timers.eventCheck = setInterval(() => {
        this.checkForEvents();
      }, GAME_CONFIG.EVENT_CHECK_INTERVAL);
    },
    
    clearTimers() {
      if (this.timers.resourceUpdate) {
        clearInterval(this.timers.resourceUpdate);
        this.timers.resourceUpdate = null;
      }
      if (this.timers.autoSave) {
        clearInterval(this.timers.autoSave);
        this.timers.autoSave = null;
      }
      if (this.timers.eventCheck) {
        clearInterval(this.timers.eventCheck);
        this.timers.eventCheck = null;
      }
    },
    
    updateResources() {
      // 每1分钟增加1/60小时的资源
      const hoursToAdd = 1 / 60;
      
      // 记录更新前的资源状态
      const prevFood = this.gameData.resources.food.amount;
      
      Object.keys(this.gameData.resources).forEach(key => {
        const resource = this.gameData.resources[key];
        // 只有非人口资源才会自动增长
        if (key !== 'population') {
          resource.amount += resource.change * hoursToAdd;
          if (resource.amount < 0) resource.amount = 0;
          if (resource.max !== null && resource.amount > resource.max) {
            resource.amount = resource.max;
          }
        }
      });
      
      // 检查是否有资源变化的重要通知
      if (this.gameData.resources.food.amount < 10 && prevFood >= 10) {
        this.showNotification('食物不足！', '警告', 'warning');
      } else if (this.gameData.resources.food.amount < 5) {
        this.showNotification('食物严重不足！村民正在挨饿！', '紧急', 'error');
        // 食物极度不足时，减少人口
        if (Math.random() < 0.3 && this.gameData.resources.population.amount > 1) {
          this.gameData.resources.population.amount -= 1;
          this.addLog('由于食物极度短缺，一名村民离开了村庄');
        }
      }
      
      // 检查是否升级村庄阶段
      this.checkVillageStage();
    },
    
    checkVillageStage() {
      const population = this.gameData.resources.population.amount;
      const buildingCount = this.gameData.buildings.filter(b => b.built).length;
      
      // 简单的阶段判定逻辑
      if (population >= 20 && buildingCount >= 4) {
        if (this.currentStage.id !== 'expansion') {
          this.currentStage = {
            id: 'expansion',
            name: '扩张阶段',
            description: '村庄开始繁荣发展'
          };
          this.showNotification('恭喜！村庄进入扩张阶段！', '里程碑', 'success');
          this.addLog('村庄进入扩张阶段');
        }
      } else if (population >= 10 && buildingCount >= 3) {
        if (this.currentStage.id !== 'development') {
          this.currentStage = {
            id: 'development',
            name: '发展阶段',
            description: '村庄开始稳定发展'
          };
          this.showNotification('恭喜！村庄进入发展阶段！', '里程碑', 'success');
          this.addLog('村庄进入发展阶段');
        }
      }
    },
    
    checkForEvents() {
      // 20%的概率触发事件
      if (Math.random() < 0.2 && this.gameData.events.filter(e => !e.resolved).length < 3) {
        this.generateRandomEvent();
      }
    },
    
    generateRandomEvent() {
      // 随机选择一个事件类型
      const randomEventType = EVENT_TYPES[Math.floor(Math.random() * EVENT_TYPES.length)];
      
      // 创建事件实例
      const newEvent = {
        id: Date.now(),
        type: randomEventType.type,
        title: randomEventType.title,
        description: randomEventType.description,
        timestamp: Date.now(),
        choices: randomEventType.choices,
        resolved: false,
        outcome: ''
      };
      
      this.gameData.events.unshift(newEvent);
      this.addLog(`新事件：${newEvent.title}`);
      this.showNotification(`新事件：${newEvent.title}`, '事件通知', 'info');
      
      // 切换到事件标签页
      if (this.currentTab !== 'events') {
        // 可以选择自动切换，或者只显示通知
        // this.switchTab('events');
      }
    },
    

    
    recruitVillager() {
      const currentPopulation = this.gameData.resources.population.amount;
      const basePopulation = 5; // 初始人口
      const popDifference = Math.max(0, currentPopulation - basePopulation);
      
      // 计算招募成本，随着人口增加而增长
      const woodCost = Math.floor(GAME_CONFIG.VILLAGER_RECRUIT_BASE_COST_WOOD *
      Math.pow(GAME_CONFIG.VILLAGER_RECRUIT_COST_GROWTH, popDifference));
      const foodCost = Math.floor(GAME_CONFIG.VILLAGER_RECRUIT_BASE_COST_FOOD *
      Math.pow(GAME_CONFIG.VILLAGER_RECRUIT_COST_GROWTH, popDifference));
      
      if (this.gameData.resources.wood.amount >= woodCost && 
          this.gameData.resources.food.amount >= foodCost && 
          currentPopulation < this.gameData.resources.population.max) {
        
        // 扣除资源
        this.gameData.resources.wood.amount -= woodCost;
        this.gameData.resources.food.amount -= foodCost;
        
        // 增加人口
        this.gameData.resources.population.amount += 1;
        
        // 生成村民名字（简单随机生成）
        const villagerNames = ['小明', '小红', '小刚', '小丽', '小张', '小李', '小王', '小刘'];
        const villagerRoles = ['农民', '工人', '木匠', '猎人', '厨师'];
        const randomName = villagerNames[Math.floor(Math.random() * villagerNames.length)];
        const randomRole = villagerRoles[Math.floor(Math.random() * villagerRoles.length)];
        
        this.addLog(`${randomName} 加入了村庄，成为一名${randomRole}！当前人口: ${currentPopulation + 1}`);
        this.showNotification(`${randomName} 加入了村庄！`, '招募成功', 'success');
        
        // 更新资源变化率（因为人口增加会增加食物消耗）
        this.updateResourceChanges();
        this.saveGame();
      } else {
        if (currentPopulation >= this.gameData.resources.population.max) {
          this.showNotification('人口已达到上限，请先升级民房', '无法招募', 'error');
        } else {
          this.showNotification(`需要 ${woodCost} 木材和 ${foodCost} 食物才能招募村民`, '资源不足', 'error');
        }
      }
    },
    
    // 快速收集资源的功能（模拟手动收集）
    collectResources() {
      // 模拟收集动画
      this.isCollecting = true;
      
      // 简单的收集逻辑：根据村民数量给予额外资源
      const population = this.gameData.resources.population.amount;
      const woodBonus = Math.floor(population * 2 * Math.random()) + 5;
      const foodBonus = Math.floor(population * 1.5 * Math.random()) + 5;
      
      // 触发粒子效果
      this.triggerCollectParticles(woodBonus, foodBonus);
      
      setTimeout(() => {
        // 添加收集的资源
        const oldWood = this.gameData.resources.wood.amount;
        const oldFood = this.gameData.resources.food.amount;
        
        this.gameData.resources.wood.amount += woodBonus;
        this.gameData.resources.food.amount += foodBonus;
        
        // 触发资源变化动画
        this.triggerResourceAnimation('wood', woodBonus, true);
        this.triggerResourceAnimation('food', foodBonus, true);
        
        this.addLog(`村民收集了 ${woodBonus} 木材和 ${foodBonus} 食物`);
        this.showNotification(`收集成功！获得 ${woodBonus} 木材和 ${foodBonus} 食物`, '收获', 'success');
        this.isCollecting = false;
        this.saveGame();
      }, 800);
    },
    
    /**
     * 触发收集粒子效果
     */
    triggerCollectParticles(woodCount, foodCount) {
      if (!this.canvasRenderer || !this.canvasEnabled) return;
      
      try {
        // 获取按钮位置（屏幕中下方）
        const buttonX = this.canvasWidth / 2;
        const buttonY = this.canvasHeight - 200;
        
        // 获取资源卡片位置（屏幕上方）
        const woodCardX = this.canvasWidth * 0.25;
        const foodCardX = this.canvasWidth * 0.75;
        const cardY = 150;
        
        // 创建木材粒子
        for (let i = 0; i < Math.min(woodCount, 20); i++) {
          setTimeout(() => {
            const particle = new Particle(
              buttonX + (Math.random() - 0.5) * 40,
              buttonY + (Math.random() - 0.5) * 40,
              woodCardX,
              cardY,
              '#92400E', // 木材颜色
              4 + Math.random() * 2
            );
            this.canvasRenderer.addParticle(particle);
          }, i * 30);
        }
        
        // 创建食物粒子
        for (let i = 0; i < Math.min(foodCount, 20); i++) {
          setTimeout(() => {
            const particle = new Particle(
              buttonX + (Math.random() - 0.5) * 40,
              buttonY + (Math.random() - 0.5) * 40,
              foodCardX,
              cardY,
              '#F59E0B', // 食物颜色
              4 + Math.random() * 2
            );
            this.canvasRenderer.addParticle(particle);
          }, i * 30);
        }
      } catch (error) {
        console.error('触发粒子效果失败:', error);
      }
    },
    
    /**
     * 触发资源变化动画
     */
    triggerResourceAnimation(type, value, isPositive) {
      if (!this.canvasRenderer || !this.canvasEnabled) return;
      
      try {
        let x, y;
        
        // 根据资源类型确定位置
        if (type === 'wood') {
          x = this.canvasWidth * 0.25;
          y = 150;
        } else if (type === 'food') {
          x = this.canvasWidth * 0.75;
          y = 150;
        } else if (type === 'population') {
          x = this.canvasWidth * 0.5;
          y = 150;
        }
        
        const animation = new ResourceAnimation(type, value, x, y, isPositive);
        this.canvasRenderer.addAnimation(animation);
      } catch (error) {
        console.error('触发资源动画失败:', error);
      }
    },
    
    // 重置游戏
    resetGame() {
      uni.showModal({
        title: '重置游戏',
        content: '确定要重置游戏吗？所有进度将丢失！',
        success: (res) => {
          if (res.confirm) {
            // 清除存储的数据
            uni.removeStorageSync(this.storageKey);
            
            // 重新初始化游戏数据
            this.initGame();
            
            this.showNotification('游戏已重置', '重置成功', 'info');
            this.addLog('游戏重置');
          }
        }
      });
    },
    
    canAffordBuilding(building) {
      const cost = building.baseCost;
      return this.gameData.resources.wood.amount >= cost && !building.built;
    },
    
    canUpgradeBuilding(building) {
      if (!building.built) return false;
      const cost = this.getUpgradeCost(building);
      return this.gameData.resources.wood.amount >= cost;
    },
    
    getUpgradeCost(building) {
      return Math.floor(building.baseCost * Math.pow(1.4, building.level));
    },
    
    upgradeBuilding(buildingId) {
      const buildingIndex = this.gameData.buildings.findIndex(b => b.id === buildingId);
      let building;
      
      if (buildingIndex === -1) {
        // 新建建筑
        const buildingType = BUILDING_TYPES.find(t => t.id === buildingId);
        if (!buildingType) return;
        
        building = {
          id: buildingId,
          level: 1,
          built: true
        };
        
        this.gameData.buildings.push(building);
        this.addLog(`成功建造了${buildingType.name}`);
        
        // 触发建筑升级特效
        this.triggerBuildingUpgradeEffect();
        
        // 民房增加人口上限
        if (buildingId === 'house') {
          this.gameData.resources.population.max += buildingType.populationIncrease;
          this.addLog(`人口上限提升至${this.gameData.resources.population.max}`);
        }
      } else {
        // 升级建筑
        building = this.gameData.buildings[buildingIndex];
        const cost = this.getUpgradeCost(building);
        
        if (this.gameData.resources.wood.amount >= cost) {
          this.gameData.resources.wood.amount -= cost;
          building.level += 1;
          
          const buildingType = BUILDING_TYPES.find(t => t.id === buildingId);
          this.addLog(`${buildingType.name}升级到了${building.level}级`);
          
          // 触发建筑升级特效
          this.triggerBuildingUpgradeEffect();
          
          // 触发资源消耗动画
          this.triggerResourceAnimation('wood', -cost, false);
          
          // 民房每级都增加人口上限
          if (buildingId === 'house' && buildingType) {
            this.gameData.resources.population.max += buildingType.populationIncrease;
            this.addLog(`人口上限提升至${this.gameData.resources.population.max}`);
          }
        }
      }
      
      this.updateResourceChanges();
      this.saveGame();
    },
    
    /**
     * 触发建筑升级特效
     */
    triggerBuildingUpgradeEffect() {
      if (!this.canvasRenderer || !this.canvasEnabled) return;
      
      try {
        // 在屏幕中心创建特效
        const x = this.canvasWidth / 2;
        const y = this.canvasHeight / 2;
        
        const effect = new BuildingUpgradeEffect(x, y);
        this.canvasRenderer.addAnimation(effect);
      } catch (error) {
        console.error('触发建筑升级特效失败:', error);
      }
    },
    
    makeChoice(eventId, choiceIndex) {
      // 简化的事件处理
      const eventIndex = this.gameData.events.findIndex(e => e.id === eventId);
      if (eventIndex === -1) return;
      
      const event = this.gameData.events[eventIndex];
      const choice = event.choices[choiceIndex];
      
      // 应用选择结果
      if (choice.effects) {
        Object.keys(choice.effects).forEach(resource => {
          if (this.gameData.resources[resource]) {
            this.gameData.resources[resource].amount += choice.effects[resource];
          }
        });
      }
      
      event.resolved = true;
      event.outcome = choice.outcome || `你选择了: ${choice.text}`;
      
      this.addLog(`处理事件: ${event.title} - ${choice.text}`);
      this.saveGame();
    },
    
    addLog(text) {
      const now = new Date();
      const timeString = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
      
      this.gameLogs.unshift({
        id: Date.now(),
        text: text,
        time: timeString
      });
      
      // 限制日志数量
      if (this.gameLogs.length > 50) {
        this.gameLogs.pop();
      }
    },
    
    showNotification(message, title = '', type = 'info') {
      this.notificationTitle = title;
      this.notificationMessage = message;
      
      const iconConfig = {
        info: { icon: 'ℹ️', color: '#6366F1' },
        success: { icon: '✅', color: '#52B788' },
        error: { icon: '❌', color: '#E63946' },
        warning: { icon: '⚠️', color: '#FB8500' }
      };
      
      const config = iconConfig[type] || iconConfig.info;
      this.notificationIcon = config.icon;
      this.notificationColor = config.color;
      
      this.notificationVisible = true;
      
      setTimeout(() => {
        this.notificationVisible = false;
      }, 3000);
    },
    
    getResourceIcon(resource) {
      const icons = {
        wood: '🪵',
        food: '🌾',
        population: '👥'
      };
      return icons[resource] || '📦';
    },
    
    getResourceName(resource) {
      const names = {
        wood: '木材',
        food: '食物',
        population: '人口'
      };
      return names[resource] || resource;
    },
    
    getBuildingIcon(buildingId) {
      const icons = {
        farm: '🚜',
        sawmill: '🪚',
        house: '🏠'
      };
      return icons[buildingId] || '🏗️';
    },
    
    getEventIcon(eventType) {
      const icons = {
        resource: '📦',
        disaster: '⚠️',
        opportunity: '🎁',
        villager: '👤'
      };
      return icons[eventType] || '📜';
    },
    

    
    // 获取村民的图标
    getVillagerIcon() {
      const icons = ['👨', '👩', '👧', '👦'];
      return icons[Math.floor(Math.random() * icons.length)];
    },
    
    // 计算村庄等级
    getVillageLevel() {
      const population = this.gameData.resources.population.amount;
      const buildings = this.gameData.buildings.filter(b => b.built).length;
      return Math.floor((population / 5) + buildings / 2) + 1;
    },
    
    formatEventTime(timestamp) {
      const date = new Date(timestamp);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
  }
}
</script>

<style>
/* ==================== CSS 变量定义（全局，非scoped） ==================== */
page {
  /* 主题色 - 活力森林绿 */
  --color-primary: #10B981;
  --color-primary-light: #34D399;
  --color-primary-dark: #059669;
  --color-secondary: #3B82F6;
  --color-accent: #F59E0B;
  --color-danger: #EF4444;
  --color-success: #10B981;
  --color-warning: #F59E0B;
  --color-info: #3B82F6;

  /* 背景色 - 清新渐变 */
  --color-bg: #F0FDF4;
  --color-surface: #FFFFFF;
  --color-surface-hover: #ECFDF5;
  --color-surface-active: #D1FAE5;

  /* 文字色 - 高对比度 */
  --color-text-primary: #064E3B;
  --color-text-secondary: #047857;
  --color-text-tertiary: #6EE7B7;
  --color-text-light: #A7F3D0;

  /* 边框色 */
  --color-border: #D1FAE5;
  --color-border-hover: #A7F3D0;

  /* 阴影 - 更立体 */
  --shadow-sm: 0 1px 2px 0 rgba(16, 185, 129, 0.05);
  --shadow-md: 0 4px 6px -1px rgba(16, 185, 129, 0.1), 0 2px 4px -1px rgba(16, 185, 129, 0.06);
  --shadow-lg: 0 10px 15px -3px rgba(16, 185, 129, 0.15), 0 4px 6px -2px rgba(16, 185, 129, 0.08);
  --shadow-xl: 0 20px 25px -5px rgba(16, 185, 129, 0.2), 0 10px 10px -5px rgba(16, 185, 129, 0.1);

  /* 渐变色 */
  --gradient-primary: linear-gradient(135deg, #10B981 0%, #059669 100%);
  --gradient-secondary: linear-gradient(135deg, #3B82F6 0%, #2563EB 100%);
  --gradient-accent: linear-gradient(135deg, #F59E0B 0%, #D97706 100%);
  --gradient-bg: linear-gradient(135deg, #F0FDF4 0%, #ECFDF5 50%, #D1FAE5 100%);

  --nav-height: 60px;
  --tabs-height: 70px;
}
</style>

<style scoped>
/* ==================== 组件样式（scoped） ==================== */

/* 全局布局 */
.mayor-log-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  background: var(--gradient-bg);
  color: var(--color-text-primary);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', sans-serif;
}

/* 游戏内容区域 */
.game-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: var(--tabs-height);
  position: relative;
}

/* Canvas动画层 */
.game-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 10;
}

/* 加载屏幕 */
.loading-screen {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 20rpx;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 8rpx solid #f3f3f3;
  border-top: 8rpx solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  color: var(--color-text-primary);
  font-size: 28rpx;
  font-weight: 600;
}

/* 标签页内容 */
.tab-content {
  display: none;
  padding: 20rpx;
}

.tab-content.active {
  display: block;
}

/* 总览页面样式 */
.overview-grid {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.resources-row {
  display: flex;
  justify-content: space-around;
  gap: 15rpx;
}

.resource-card {
  flex: 1;
  background: var(--color-surface);
  border-radius: 24rpx;
  padding: 24rpx 16rpx;
  box-shadow: var(--shadow-md);
  text-align: center;
  position: relative;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 2rpx solid var(--color-border);
}

.resource-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4rpx;
  background: var(--gradient-primary);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.resource-card:active {
  transform: scale(0.98);
  box-shadow: var(--shadow-sm);
}

.resource-card:active::before {
  transform: scaleX(1);
}

.resource-icon {
  display: block;
  font-size: 50rpx;
  margin-bottom: 10rpx;
}

.resource-name {
  display: block;
  font-size: 24rpx;
  color: var(--color-text-secondary);
  margin-bottom: 8rpx;
}

.resource-value {
  display: block;
  font-size: 40rpx;
  font-weight: bold;
  color: var(--color-text-primary);
  margin-bottom: 5rpx;
}

.resource-change {
  display: block;
  font-size: 20rpx;
}

.resource-change.positive {
  color: var(--color-success);
}

.resource-change.negative {
  color: var(--color-danger);
}

.info-cards-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15rpx;
}

.info-card-small {
  background: var(--color-surface);
  border-radius: 20rpx;
  padding: 24rpx;
  box-shadow: var(--shadow-md);
  border: 2rpx solid var(--color-border);
  transition: all 0.3s ease;
}

.info-card-small:active {
  transform: scale(0.98);
  box-shadow: var(--shadow-sm);
}

.info-card-label {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 10rpx;
}

.info-icon {
  font-size: 28rpx;
}

.info-text {
  font-size: 24rpx;
  color: var(--color-text-secondary);
}

.info-card-value {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: var(--color-text-primary);
}

.quick-actions {
  display: flex;
  gap: 20rpx;
}

.btn {
  flex: 1;
  border: none;
  border-radius: 20rpx;
  padding: 25rpx;
  font-size: 28rpx;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  transition: all 0.3s ease;
  min-width: 200rpx;
}

.btn:active {
  transform: scale(0.95);
}

.btn-primary {
  background: var(--gradient-primary);
  color: white;
  box-shadow: var(--shadow-md);
  position: relative;
  overflow: hidden;
}

.btn-primary::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  transform: translate(-50%, -50%);
  transition: width 0.6s, height 0.6s;
}

.btn-primary:active::before {
  width: 300rpx;
  height: 300rpx;
}

.btn-secondary {
  background: var(--gradient-secondary);
  color: white;
  box-shadow: var(--shadow-md);
  position: relative;
  overflow: hidden;
}

.btn-secondary::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  transform: translate(-50%, -50%);
  transition: width 0.6s, height 0.6s;
}

.btn-secondary:active::before {
  width: 300rpx;
  height: 300rpx;
}

.btn:disabled {
  background: #BDC3C7;
  color: #7F8C8D;
}

.btn-icon {
  font-size: 32rpx;
}

.btn-text {
  font-size: 28rpx;
}

/* 建筑页面样式 */
.content-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.building-card {
  background: var(--color-surface);
  border-radius: 24rpx;
  padding: 28rpx;
  box-shadow: var(--shadow-md);
  border: 2rpx solid var(--color-border);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.building-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6rpx;
  background: var(--gradient-primary);
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 0.3s ease;
}

.building-card:active {
  transform: translateY(-4rpx);
  box-shadow: var(--shadow-lg);
}

.building-card:active::before {
  transform: scaleX(1);
}

.building-header {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.building-icon {
  font-size: 50rpx;
}

.building-info {
  flex: 1;
}

.building-name {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: var(--color-text-primary);
  margin-bottom: 5rpx;
}

.building-level {
  font-size: 24rpx;
  color: var(--color-text-secondary);
}

.building-details {
  margin-bottom: 20rpx;
}

.building-description {
  display: block;
  font-size: 24rpx;
  color: var(--color-text-secondary);
  line-height: 1.4;
  margin-bottom: 15rpx;
}

.building-stats {
  display: flex;
  gap: 15rpx;
  flex-wrap: wrap;
}

.stat-item {
  background: var(--color-surface-hover);
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
  font-size: 22rpx;
  color: var(--color-primary);
}

/* 事件页面样式 */
.events-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 事件Tab */
.event-tabs {
  display: flex;
  background: var(--color-surface);
  border-radius: 16rpx;
  padding: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: var(--shadow-sm);
}

.event-tab {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 16rpx 24rpx;
  border-radius: 12rpx;
  transition: all 0.2s ease;
  position: relative;
  cursor: pointer;
}

.event-tab:active {
  transform: scale(0.96);
  opacity: 0.8;
}

.event-tab.active {
  background: var(--gradient-primary);
  box-shadow: var(--shadow-sm);
}

.event-tab.active .event-tab-text {
  color: white;
  font-weight: bold;
}

.event-tab.active .event-tab-badge {
  background: rgba(255, 255, 255, 0.3);
  color: white;
}

.event-tab-text {
  font-size: 28rpx;
  color: var(--color-text-secondary);
  transition: all 0.3s ease;
}

.event-tab-badge {
  background: var(--color-primary-light);
  color: white;
  font-size: 20rpx;
  font-weight: bold;
  padding: 2rpx 10rpx;
  border-radius: 20rpx;
  min-width: 32rpx;
  text-align: center;
}

/* 事件列表 */
.events-list {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.event-card {
  background: var(--color-surface);
  border-radius: 20rpx;
  padding: 24rpx;
  box-shadow: var(--shadow-md);
  border: 2rpx solid var(--color-border);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: visible;
}

.event-card.resolved {
  opacity: 0.8;
  background: var(--color-surface-hover);
}

.event-header {
  display: flex;
  align-items: flex-start;
  gap: 12rpx;
  margin-bottom: 12rpx;
}

.event-icon {
  font-size: 32rpx;
  flex-shrink: 0;
}

.event-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.event-title {
  font-size: 28rpx;
  font-weight: bold;
  color: var(--color-text-primary);
  line-height: 1.3;
}

.event-time {
  font-size: 20rpx;
  color: var(--color-text-tertiary);
}

.event-description {
  display: block;
  font-size: 24rpx;
  color: var(--color-text-secondary);
  line-height: 1.5;
  margin-bottom: 16rpx;
}

/* 横向滚动的选项容器 */
.event-choices-scroll {
  width: 100%;
  white-space: nowrap;
}

.event-choices-horizontal {
  display: inline-flex;
  gap: 12rpx;
  padding: 4rpx 0;
}

.choice-btn-horizontal {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 28rpx;
  background: var(--gradient-secondary);
  color: white;
  border-radius: 16rpx;
  border: none;
  font-size: 24rpx;
  font-weight: 500;
  white-space: nowrap;
  box-shadow: var(--shadow-sm);
  transition: all 0.3s ease;
}

.choice-btn-horizontal:active {
  transform: scale(0.95);
  box-shadow: var(--shadow-md);
}

.choice-btn-text {
  font-size: 24rpx;
}

.event-outcome {
  display: flex;
  align-items: center;
  gap: 12rpx;
  background: var(--color-surface-hover);
  padding: 16rpx;
  border-radius: 12rpx;
  border-left: 4rpx solid var(--color-success);
}

.outcome-icon {
  font-size: 24rpx;
  color: var(--color-success);
}

.outcome-text {
  flex: 1;
  font-size: 24rpx;
  color: var(--color-text-secondary);
  line-height: 1.4;
}

/* 小型空状态 */
.empty-state-small {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 40rpx;
  text-align: center;
}

.empty-icon-small {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text-small {
  font-size: 26rpx;
  color: var(--color-text-tertiary);
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 40rpx;
  text-align: center;
}

.empty-icon {
  font-size: 100rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: var(--color-text-primary);
  margin-bottom: 15rpx;
}

.empty-subtext {
  display: block;
  font-size: 26rpx;
  color: var(--color-text-secondary);
  line-height: 1.4;
}

/* 日志页面样式 */
.logs-container {
  background: var(--color-surface);
  border-radius: 24rpx;
  padding: 28rpx;
  box-shadow: var(--shadow-md);
  border: 2rpx solid var(--color-border);
  max-height: 80vh;
  overflow-y: auto;
}

.logs-container::-webkit-scrollbar {
  width: 8rpx;
}

.logs-container::-webkit-scrollbar-track {
  background: var(--color-surface-hover);
  border-radius: 4rpx;
}

.logs-container::-webkit-scrollbar-thumb {
  background: var(--color-primary-light);
  border-radius: 4rpx;
}

.logs-container::-webkit-scrollbar-thumb:hover {
  background: var(--color-primary);
}

.log-item {
  display: flex;
  gap: 15rpx;
  padding: 15rpx 0;
  border-bottom: 1px solid var(--color-border);
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  font-size: 22rpx;
  color: var(--color-text-tertiary);
  min-width: 100rpx;
}

.log-text {
  flex: 1;
  font-size: 24rpx;
  color: var(--color-text-secondary);
  line-height: 1.4;
}

/* 底部标签页导航 */
.main-tabs-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: var(--tabs-height);
  background: var(--color-surface);
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  z-index: 99;
}

.main-tab {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 5rpx;
  position: relative;
}

.main-tab {
  transition: all 0.3s ease;
}

.main-tab.active {
  color: var(--color-primary);
}

.main-tab::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 4rpx;
  background: var(--color-primary);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.main-tab.active::after {
  transform: scaleX(1);
}

.tab-icon {
  font-size: 40rpx;
  transition: color 0.3s ease;
}

.tab-text {
  font-size: 22rpx;
  transition: color 0.3s ease;
}

.main-tab.active .tab-icon,
.main-tab.active .tab-text {
  color: var(--color-primary);
}

/* 通知样式 */
.notification {
  position: fixed;
  top: 100rpx;
  left: 50%;
  transform: translateX(-50%) translateY(-80rpx);
  background: var(--color-surface);
  border-radius: 20rpx;
  padding: 28rpx 32rpx;
  box-shadow: var(--shadow-xl);
  border: 2rpx solid var(--color-border);
  display: flex;
  align-items: center;
  gap: 24rpx;
  max-width: 85%;
  opacity: 0;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 1000;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
}

.notification.show {
  opacity: 1;
  transform: translateX(-50%) translateY(0);
  animation: bounce-in 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}

@keyframes bounce-in {
  0% {
    transform: translateX(-50%) translateY(-80rpx) scale(0.8);
    opacity: 0;
  }
  50% {
    transform: translateX(-50%) translateY(10rpx) scale(1.05);
  }
  100% {
    transform: translateX(-50%) translateY(0) scale(1);
    opacity: 1;
  }
}

.notification-icon {
  font-size: 40rpx;
  flex-shrink: 0;
}

.notification-content {
  flex: 1;
}

.notification-title {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: var(--color-text-primary);
  margin-bottom: 5rpx;
}

.notification-message {
  display: block;
  font-size: 24rpx;
  color: var(--color-text-secondary);
}
</style>